#ifndef _M_LOG_H__
#define _M_LOG_H__

#include <iostream>
#include <string>
#include <ctime>
#include <cstring>
#include <stdarg.h>
#include <unistd.h>

using namespace std;

#define LOG_NORMAL "log.txt"
#define LOG_ERR "log.error"
#define NUM 1024

#define DEBUG 0
#define NORMAL 1
#define WARNING 2
#define ERROR 3
#define FATAL 4

const char *to_levelstr(int level)
{
    switch (level)
    {
    case DEBUG:
        return "DEBUG";
    case NORMAL:
        return "NORMAL";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return nullptr;
    }
}

const char* to_time()
{
    std::string time_now = "";
   // 基于当前系统的当前日期/时间
   time_t now = time(0);
   tm *ltm = localtime(&now);
   time_now += to_string(1900 + ltm->tm_year);
   time_now += "年";
   time_now += to_string(1 + ltm->tm_mon);
   time_now += "月";
   time_now += to_string(ltm->tm_mday);
   time_now += "日";
   time_now += to_string(ltm->tm_hour);
   time_now += "时";
   time_now += to_string(ltm->tm_min);
   time_now += "分";
   time_now += to_string(ltm->tm_sec);
   time_now += "秒";
   return time_now.c_str();
}

void logMessage(int level, const char *format, ...)
{
    //[日志等级][事件][pid][message]
    char logprefix[NUM];
    snprintf(logprefix, sizeof(logprefix), "[%s][%s][pid:%d]", to_levelstr(level), to_time(), getpid());

    char logcontent[NUM];
    va_list arg;
    va_start(arg,format);
    vsnprintf(logcontent,sizeof(logcontent),format,arg);

    //向文件中输出日志信息
    FILE *log = fopen(LOG_NORMAL, "a");
    FILE *err = fopen(LOG_ERR, "a");
    if (log != nullptr && err != nullptr)
    {
        FILE* curr = nullptr;
        if(level == DEBUG || level == NORMAL || level == WARNING) curr = log;
        if(level == ERROR || level == FATAL) curr = err;
        if(curr) fprintf(curr,"%s%s\n",logprefix,logcontent);
        fclose(log);
        fclose(err);
    }
}

#endif